﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Aliyun.OSS;
using dayingjia.Common;

namespace Chire.ChireInter.Other
{
    /// <summary>
    /// fileupload 的摘要说明
    /// </summary>
    public class fileupload : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            Oss oss = new Oss();
            HttpPostedFile _upfile = context.Request.Files["File"];
            if (_upfile == null)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"请选择要上传的图片！\"}");
                return;
            }

            string fileExt = GetFileExt(_upfile.FileName); //文件扩展名，不含“.” 
            //检查文件扩展名是否合法
       
            string newFileName = oss.GetUpLoadPath() + GetRamCode() + "." + fileExt; //随机生成新的文件名
            //_upfile.SaveAs(relationPath + newFileName);
            oss.Upload(newFileName, _upfile.InputStream);
            context.Response.Write("{\"status\": 1, \"msg\": \"上传文件成功！\", \"name\": \""
                + _upfile.FileName + "\", \"path\": \"" + newFileName + "\", \"size\": " + _upfile.ContentLength + ", \"ext\": \"" + fileExt + "\"}");

            context.Response.End();
        }

        public string GetFileExt(string _filepath)
        {
            if (string.IsNullOrEmpty(_filepath))
            {
                return "";
            }
            if (_filepath.LastIndexOf(".") > 0)
            {
                return _filepath.Substring(_filepath.LastIndexOf(".") + 1); //文件扩展名，不含“.”
            }
            return "";
        }

        /// <summary>
        /// 是否为图片文件
        /// </summary>
        /// <param name="_fileExt">文件扩展名，不含“.”</param>
        public bool IsImage(string _fileExt)
        {
            ArrayList al = new ArrayList();
            al.Add("bmp");
            al.Add("jpeg");
            al.Add("jpg");
            al.Add("gif");
            al.Add("png");
            al.Add("txt");
            al.Add("text");
            if (al.Contains(_fileExt.ToLower()))
            {
                return true;
            }
            return false;
        }

        public string GetRamCode()
        {
            return DateTime.Now.ToString("yyyyMMddHHmmssffff");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}